﻿using PARK.Common.Core.Manager;
using PARK.Common.Enum;
using PARK.Common.Extension;
using PARK.Common.Filter;
using PARK.Dependency;
using PARK.DynamicApiController;
using PARK.FriendlyException;
using Mapster;
using Microsoft.AspNetCore.Mvc;
using SqlSugar;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Yitter.IdGenerator;
using PARK.Common.Helper;
using PARK.JsonSerialization;
using PARK.Accessctl.Entitys;
using PARK.Accessctl.Interfaces.AccessRemotedoor;
using PARK.Accessctl.Entitys.Dto.AccessRemotedoor;
using PARK.System.Interfaces.Permission;
using PARK.Common.Util;

namespace PARK.Accessctl.AccessRemotedoor
{
    /// <summary>
    /// 远程开门服务
    /// </summary>
    [ApiDescriptionSettings(Tag = "Access", Name = "Remotedoor", Order = 200)]
    [Route("api/access/[controller]")]
    public class AccessRemotedoorService : IAccessRemotedoorService, IDynamicApiController, ITransient
    {
        private readonly ISqlSugarRepository<AccessRemotedoorEntity> _accessRemotedoorRepository;
        private readonly SqlSugarScope _db;
        private readonly IUserManager _userManager;
        private readonly IOrganizeService _organizeService; // 机构表仓储

        /// <summary>
        /// 初始化一个<see cref="AccessRemotedoorService"/>类型的新实例
        /// </summary>
        public AccessRemotedoorService(
            ISqlSugarRepository<AccessRemotedoorEntity> accessRemotedoorRepository,
            IUserManager userManager,
             IOrganizeService organizeService)
        {
            _accessRemotedoorRepository = accessRemotedoorRepository;
            _db = _accessRemotedoorRepository.Context;
            _userManager = userManager;
            _organizeService = organizeService;
        }

        /// <summary>
        /// 获取远程开门记录
        /// </summary>
        /// <param name="id">参数</param>
        /// <returns></returns>
        [HttpGet("{id}")]
        public async Task<dynamic> GetInfo(string id)
        {
            var entity = await _db.Queryable<AccessRemotedoorEntity>().FirstAsync(p => p.Id == id);
            var output = entity.Adapt<AccessRemotedoorInfoOutput>();
            return output;
        }

        /// <summary>
		/// 获取远程开门记录列表
		/// </summary>
		/// <param name="input">请求参数</param>
		/// <returns></returns>
        [HttpGet("")]
        public async Task<dynamic> GetList([FromQuery] AccessRemotedoorListQueryInput input)
        {
            var userInfo = await _userManager.GetUserInfo();
            var sidx = input.sidx == null ? "id" : input.sidx;
            var organizeIds = new List<string>();
            if (!input.organizeId.IsNullOrEmpty())
                organizeIds = await GetSubOrganizeIds(input.organizeId);
            //选中公司查询全部
            if (input.departId == "96240625-934F-490B-8AA6-0BC775B18468")
            {
                input.departId = null;
            }
            //开门日期
            List<string> queryBillDate = input.passtime != null ? input.passtime.Split(',').ToObeject<List<string>>() : null;
            DateTime? startBilldate = queryBillDate != null ? Ext.GetDateTime(queryBillDate.First()) : null;
            DateTime? endBilldate = queryBillDate != null ? Ext.GetDateTime(queryBillDate.Last()) : null;

            var data = await _db.Queryable<AccessRemotedoorEntity>()
                .Where(p => p.CompanyId.Equals(userInfo.companyId))//权限
                //关键字查询
                .WhereIF(!input.keyword.IsNullOrEmpty(), p => p.CtlSn.Contains(input.keyword)|| p.JobNo.Contains(input.keyword) || p.ReallName.Contains(input.keyword) || p.DoorNo.Contains(input.keyword))
                .WhereIF(!string.IsNullOrEmpty(input.passStatus), p => p.PassStatus.Equals(input.passStatus))
                .WhereIF(!string.IsNullOrEmpty(input.departId), p => p.DepartId.Equals(input.departId))
                .WhereIF(!string.IsNullOrEmpty(input.doorid), p => p.DoorNo.Contains(input.doorid))
                //所在区域
                .WhereIF(!string.IsNullOrEmpty(input.doorAreaName), p => p.DoorAreaId.Equals(input.doorAreaName))
                //组织机构
                .WhereIF(organizeIds.Any(), u => organizeIds.Contains(SqlFunc.ToString(u.DepartId)))
                //开门日期查询
                .WhereIF(queryBillDate != null, a => a.Passtime >= new DateTime(startBilldate.ToDate().Year, startBilldate.ToDate().Month, startBilldate.ToDate().Day, 0, 0, 0))
                .WhereIF(queryBillDate != null, a => a.Passtime <= new DateTime(endBilldate.ToDate().Year, endBilldate.ToDate().Month, endBilldate.ToDate().Day, 23, 59, 59))
                .Select(it => new AccessRemotedoorListOutput
                {
                    id = it.Id,
                    ctlSn = it.CtlSn,
                    ctlInex = it.CtlInex,
                    passtime = Convert.ToDateTime(it.Passtime).ToString("yyyy-MM-dd HH:mm:dd"),
                    doorNo = it.DoorNo,
                    doorName = it.DoorName,
                    passStatus = it.PassStatus,
                    passStatusName = it.PassStatusName,
                    description = it.Description,
                    jobNo = it.JobNo,
                    reallName = it.ReallName,
                    departId = it.DepartId,
                    departName = it.DepartName,
                    doorAreaName = it.DoorAreaName,
                    ctlposition = it.Ctlposition,
                }).MergeTable().OrderBy(sidx + " " + input.sort).ToPagedListAsync(input.currentPage, input.pageSize);
            return PageResult<AccessRemotedoorListOutput>.SqlSugarPageResult(data);
        }

        /// <summary>
        /// 下属机构
        /// </summary>
        /// <param name="organizeId">机构ID</param>
        /// <returns></returns>
        [NonAction]
        public async Task<List<string>> GetSubOrganizeIds(string organizeId)
        {
            var data = await _organizeService.GetListAsync();
            data = data.TreeChildNode(organizeId, t => t.Id, t => t.ParentId);
            return data.Select(m => m.Id).ToList();
        }

        /// <summary>
        /// 新建远程开门记录
        /// </summary>
        /// <param name="input">参数</param>
        /// <returns></returns>
        [HttpPost("")]
        public async Task Create([FromBody] AccessRemotedoorCrInput input)
        {
            var userInfo = await _userManager.GetUserInfo();
            var entity = input.Adapt<AccessRemotedoorEntity>();
            entity.Id = YitIdHelper.NextId().ToString();
            entity.CompanyId = userInfo.companyId;
            entity.CompanyName = userInfo.companyName;
            var isOk = await _db.Insertable(entity).IgnoreColumns(ignoreNullColumn: true).ExecuteCommandAsync();
            if (!(isOk > 0)) throw JNPFException.Oh(ErrorCode.COM1000);
        }

        /// <summary>
        /// 更新门禁记录
        /// </summary>
        /// <param name="id">主键</param>
        /// <param name="input">参数</param>
        /// <returns></returns>
        [HttpPut("{id}")]
        public async Task Update(string id, [FromBody] AccessRemotedoorUpInput input)
        {
            var entity = input.Adapt<AccessRemotedoorEntity>();
            var isOk = await _db.Updateable(entity).IgnoreColumns(ignoreAllNullColumns: true).ExecuteCommandAsync();
            if (!(isOk > 0)) throw JNPFException.Oh(ErrorCode.COM1001);
        }

        /// <summary>
        /// 删除远程开门记录
        /// </summary>
        /// <returns></returns>
        [HttpDelete("{id}")]
        public async Task Delete(string id)
        {
            var entity = await _db.Queryable<AccessRemotedoorEntity>().FirstAsync(p => p.Id == id);
            _ = entity ?? throw JNPFException.Oh(ErrorCode.COM1005);
            var isOk = await _db.Deleteable<AccessRemotedoorEntity>().Where(d => d.Id == id).ExecuteCommandAsync();
            if (!(isOk > 0)) throw JNPFException.Oh(ErrorCode.COM1002);
        }
    }
}
